#!/usr/bin/python
# -*- coding:utf-8 -*-
#generate_pro.py
# lingyue.wkl@taobao.com or wukunliang@163.com
#created 2011-10-23 version0.1
#rebuild all functions 2012-03-09 version0.2

import os,sys,getopt,time

COLOR_NONE = "\033[m"
COLOR_GREEN = "\033[01;32m"
COLOR_RED = "\033[01;31m"
COLOR_YELLOW = "\033[01;33m"

def main():
    try:
        opts,args = getopt.getopt(sys.argv[1:],"i:hs")

        for op,value in opts:
          if op in ("-h","-H","--help"):
            help_msg()
          if op == "-i":
            inpath = value
          elif op == "-s":
            sourcepath = value

          if len(opts) < 1:
            print(sys.argv[0]+" : the amount of params must great equal than 1")
            sys.exit(1)
    except getopt.GetoptError:
      print(sys.argv[0]+" : params are not defined well!")

    if 'inpath' not in dir():
      print("-i inpath needed!")
      sys.exit(1)

    if 'sourcepath' not in dir():
      sourcepath = "./example"

    if inpath.startswith("http://") and inpath.endswith(".rpm"):
      rpm_url = inpath
    else:
      print(COLOR_RED + "Error: The wrong rpm url,can't process!" + COLOR_NONE)
      sys.exit(1)

    rpm_file_name = os.path.split(rpm_url)[1]
    pro_name = "-".join(rpm_file_name.split("-")[:-2])[9:]

    if os.path.exists(pro_name):
      print(COLOR_YELLOW + "Warning: Project dir is already exists! I will create a new one for you!" + COLOR_NONE)
      time_stamp = time.strftime('%Y%m%d%H%M%S',time.localtime())
      pro_name = pro_name +"_" + time_stamp

    print("Generate project dir " + COLOR_GREEN + pro_name + COLOR_NONE)
    if os.system("cp -r " + sourcepath + " ./" + pro_name) == 0:
      print(COLOR_GREEN + "Copy success!" + COLOR_NONE)
    else:
      print(COLOR_RED + "Copy failed!" + COLOR_NONE)

    os.chdir(pro_name)

    print("Sed CONST params and package check......")
    print("")
    if os.system("./"+"package_checker.py -i " + rpm_url + " -s") == 0:
      print(COLOR_GREEN + "Check success!" + COLOR_NONE)
    else:
      print(COLOR_RED + "Check failed!" + COLOR_NONE)


if __name__ == "__main__":
  main()
